<?php
class Framework {
	public static function run(){
		//echo "hello,world";
		self::init();
		self::autoload();
		self::dispatch();
	}

	//初始化
	private static function init(){
		// 定义路径常量
		define("DS", DIRECTORY_SEPARATOR);
		define("ROOT", getcwd() . DS);//根目录
		define("APP_PATH", ROOT. 'application' .DS);
		define("FRAMEWORK_PATH", ROOT . "framework" .DS);
		define("PUBLIC_PATH", ROOT . 'public' .DS);
		define("CONFIG_PATH", APP_PATH . "config" .DS);
		define("MODEL_PATH", APP_PATH . "models" .DS);
		define("VIEW_PATH", APP_PATH . "views" .DS);
		define("CONTROLLER_PATH", APP_PATH . "controllers" .DS);
		define("CORE_PATH", FRAMEWORK_PATH  . "core" .DS);
		define("LIB_PATH", FRAMEWORK_PATH . "libraries" .DS);
		define("DB_PATH", FRAMEWORK_PATH . "databases" .DS);
		define("HELPER_PATH", FRAMEWORK_PATH . "helpers" .DS);
		define("UPLOAD_PATH", PUBLIC_PATH . "uploads" .DS);
		//index.php?p=admin&c=goods&a=add 对应 GoodsController
		define("PLATFORM",isset($_REQUEST['p']) ? $_REQUEST['p'] : 'admin' );
		define("CONTROLLER", isset($_REQUEST['c']) ? ucfirst($_REQUEST['c']) : 'Index');
		define("ACTION", isset($_REQUEST['a']) ? $_REQUEST['a'] : 'index' );
		define("CUR_CONTROLLER_PATH", CONTROLLER_PATH . PLATFORM .DS);
		define("CUR_VIEW_PATH", VIEW_PATH . PLATFORM . DS);

		//加载核心类
		include CORE_PATH . "Controller.class.php";
		include CORE_PATH . "Model.class.php";
		include DB_PATH . "Mysql.class.php";

		//加载配置文件
		$GLOBALS['config'] = include CONFIG_PATH . "config.php";

		//开启session
		session_start();
	}

	//实现自动加载
	private static function autoload(){
		spl_autoload_register(array(__CLASS__,'load'));
	}

	//普通的方法，完成加载功能  如GoodsController GoodsModel
	//此处的自动加载只针对application中的controller和model
	private static function load($classname){
		if (substr($classname, -10) == 'Controller') {
			// 是控制器
			include CUR_CONTROLLER_PATH . "{$classname}.class.php";
 		} elseif (substr($classname, -5) == 'Model') {
 			// 是模型
 			include MODEL_PATH . "{$classname}.class.php";
 		} else {
 			// 暂略
 		}
	}

	//路由分发,说白了，就是实例化对象，并调用方法
	//index.php?p=admin&c=goods&a=add GoodsController 中的 addAction
	private static function dispatch(){
		//获取控制器和方法的名字
		$controller_name = CONTROLLER . "Controller";
		$action_name = ACTION . "Action";
		//实例化对象
		$controller = new $controller_name();
		//调用方法
		$controller->$action_name();
	}
}